package org.vison.wonfu.framework.soa.context;

import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

public class ContextAttachment {
    protected final ConcurrentMap<String, Object> attachments = new ConcurrentHashMap<>();

    public ConcurrentMap<String, Object> getAttachments() {
        return attachments;
    }

    public void putAttachment(String key, Object value) {
        attachments.put(key, value);
    }

    public void putAttachmentIfAbsent(String key, Object value) {
        attachments.putIfAbsent(key, value);
    }

    public void putAllAttachments(Map<String, Object> map) {
        if (map == null) {
            return;
        }
        this.attachments.putAll(map);
    }


    Object removeAttachment(String key) {
        return attachments.remove(key);
    }

    public Object getAttachment(String key) {
        return attachments.get(key);
    }

    public Object getAttachment(String key, Object defaultValue) {
        return attachments.getOrDefault(key, defaultValue);
    }

    public String getAttachmentString(String key) {
        return getAttachmentString(key, null);
    }

    public String getAttachmentString(String key, String defaultValue) {
        return Optional.of(attachments)
                .map(a -> a.get(key))
                .filter(v -> v instanceof String)
                .map(Object::toString)
                .orElse(defaultValue);
    }

    /**
     * deep copy
     **/
    public ContextAttachment copy() {
        ContextAttachment copy = new ContextAttachment();

        if (!this.attachments.isEmpty()) {
            copy.attachments.putAll(this.attachments);
        }

        return copy;
    }
}
